<?php

include '_portal.php';

$method = POST_ARR['method'];
$payload = POST_ARR['payload'];

switch ($method) {
case 'record':
  output(record($payload));
  break;
case 'query':
  output(query($payload));
  break;
default:
  output(['status' => 0, 'msg' => 'Invalid method']);

}

/*
payload: {
acid: "",
seat: "TM01",
frequency: 124.85,
dateTime: new Date(),
moment: dayjs().format("YYYY-MM-DD HH:mm:ss"),
stage: 3,
speedCleared: 160,
speedExecuted: 180,
effect: 0,
description: "",
}
 */

function record($payload) {
  create_table();
  $acid = $payload['acid'];
  $company = $payload['company'];
  $seat = $payload['seat'];
  $frequency = $payload['frequency'];
  $moment = $payload['moment'];
  $stage = $payload['stage'];
  $pos = $payload['finalPosition'];
  $speed = $payload['speedCleared'];
  $speed2 = $payload['speedExecuted'];
  $effect = $payload['effect'];
  $mis = $payload['missedApproach'];
  $description = $payload['description'];
  $ip = get_client_ip();
  $sql = "INSERT INTO `2kt_journal_speed`(`acid`, `company`, `seat`, `frequency`, `moment`, `stage`, `pos`, `speed`, `speed2`, `effect`, `mis`, `description`, `ip`) VALUES ('{$acid}','{$company}','{$seat}',{$frequency},'{$moment}',{$stage},{$pos},{$speed},{$speed2},{$effect},{$mis},'{$description}','{$ip}')";
  $result = exec_sql($sql);
  return ['status' => $result ? 1 : 0, 'sql' => $result ? '' : $sql];
}

function query($payload) {
  create_table();
  $start = $payload['start'];
  $end = $payload['end'];
  $sql = "SELECT * FROM `2kt_journal_speed` WHERE `moment`>='{$start}' AND `moment` <='{$end}'";
  $result = exec_sql($sql);
  return ['status' => $result ? 1 : 0, 'content' => $result ?: []];
}

function create_table() {
  return exec_sql("CREATE TABLE IF NOT EXISTS `2kt_journal_speed` (`number` int(11) NOT NULL,`acid` varchar(12) COLLATE utf8_unicode_ci NOT NULL,`company` varchar(8) COLLATE utf8_unicode_ci NOT NULL,`seat` varchar(8) COLLATE utf8_unicode_ci NOT NULL,`frequency` decimal(6,3) NOT NULL,`moment` datetime NOT NULL,`stage` int(2) NOT NULL,`pos` int(4) NOT NULL DEFAULT '0',`speed` int(4) NOT NULL,`speed2` int(4) NOT NULL,`effect` int(2) NOT NULL,`mis` int(4) NOT NULL DEFAULT '0',`description` text COLLATE utf8_unicode_ci NOT NULL,`ip` varchar(24) COLLATE utf8_unicode_ci NOT NULL,`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
}